﻿
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using NetCore.Code.BLL;
using NetCore.Code.Model;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;

namespace NetCore.Code.Web.Controllers
{
    public class HomeController : AreaController
    {
        #region Service注入

        public IDbServerService mService { get; set; }
        public ICodeDbTypeService mSysDbTypeService { get; set; }
        public IDbColumnService mDbColumnService { get; set; }

        public IDbTableService mTService { get; set; }
        public IDbServerService mSService { get; set; }

        public IDbCodeService mCService { get; set; }

        public IDbTypeService dbTypeService { get; set; }

        public IDbTemplateService dTService { get; set; }
        #endregion
        [Permission]
        public IActionResult Index()
        {

            return View();
        }

        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult ForGrid(LigerGrid grid,int id)
        {
            grid.Rows= mCService.GetColumns( id);
            return Json(grid);
        }

        [Permission(IsParent = true)]
        public IActionResult Edit(string id, DbServerEntity entity)
        {

            return View();
        }
        [HttpPost]
        [Permission(NoAccess =true)]
        public JsonResult Delete(string deleteKeys)
        {
            return Json(AjaxResult.Success());
        }
        [Permission(ActionName = "DbDelete")]
        [HttpPost]
        public JsonResult DbColumnDelete(string deleteKeys)
        {
            string strError = "";
            if (mDbColumnService.Delete(deleteKeys, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            else
            {
                return Json(AjaxResult.Error(strError));
            }
        }
        [Permission("01","删除")]
        [HttpPost]
        public JsonResult DbDelete(string sourceId, string dbServerType)
        {
            string strError = "";
            if (mCService.DbDelete(sourceId, dbServerType, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            else
            {
                return Json(AjaxResult.Error(strError));
            }
        }
        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult GetTree(string parentid,string action="T",int dbServerType=0)
        {
            if (dbServerType == 0)
            {
                var lstServer = mService.GetAll();
                if (lstServer != null && lstServer.Count > 0)
                {
                    lstServer.ForEach(x =>
                    {
                        x.parent = "0_S";
                    });
                }
                DbServerEntity entity = new DbServerEntity
                {
                    DbServerId = 0,
                    DbServerName = "DBManagerList",
                    LocalName = "服务器列表",
                 
                    ProviderType = -1,

                    ConntionString = "",
                    children = lstServer.ToArray()
                };
                return Json(AjaxResult.Success(entity));
            }
            else if (dbServerType == 1)
            {
                var lstTable = mCService.GetDbTable(parentid.ToInt(), action.ToUpper().Equals("T"));

                return Json(AjaxResult.Success(lstTable));
            }
            else
            {
                var lstItems= new object[] {
                    new { text = "字段", id = parentid.ToString()+"_C" ,icon="fa fa-columns" ,parent=parentid+"_DT", SourceId = parentid.ToString(), DbServerType = 3, action = "1",children=false },
                    new { text = "数据",id = parentid.ToString()+"_D",icon="fa fa-list-alt", SourceId = parentid.ToString(),parent=parentid+"_DT", DbServerType = 3, action = "2",children=false } };
                return Json(AjaxResult.Success(lstItems));
            }
           
        }
        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult GetTreeTable(int id)
        {

            return Json(mCService.GetDbTable(id, true));
        }
        [HttpPost]
        [Permission(IsParent =true)]
        public JsonResult GetTreeView(int id)
        {

            return Json(mCService.GetDbTable(id, false));
        }
       
        [Permission("02","编辑",IsPost=true)]
        [HttpPost]
        public JsonResult SaveColumns(string list)
        {
            List<DbColumnEntity> lst = JSONHelper.FromJson <List<DbColumnEntity> >( list);
            string strError = "";

            if (mDbColumnService.Save(lst, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            return Json(AjaxResult.Error(strError));
        }
      
        [Permission(IsPost =true,ActionName = "SaveColumns")]
        public IActionResult DbServer(DbServerEntity entity,string id)
        {
            if (!this.IsPost)
            {
                if (!string.IsNullOrWhiteSpace(id))
                {
                    entity = mService.GetById(id);
                }
                if (entity == null)
                {
                    entity = new DbServerEntity
                    {

                    };
                }
            }
            else
            {
                string strError = "";
                if (mService.Save(entity, ref strError))
                {
                    entity.parent = "0_S";
                    return Json(AjaxResult.Success(entity));
                }
                return Json(AjaxResult.Error(strError));
            }
            return View(entity);
        }
        [Permission(IsPost = true, ActionName = "SaveColumns")]
        public IActionResult DbTable(DbTableEntity entity,string id)
        {
            if (!this.IsPost)
            {
                if (!string.IsNullOrWhiteSpace(id))
                {
                    entity = mTService.GetById(id);
                }
                if (entity == null)
                {
                    entity = new DbTableEntity
                    {

                    };
                }
            }
            else
            {
                string strError = "";
                if (mCService.DbTableSave(entity, ref strError))
                {
                    return Json(AjaxResult.Success(entity));
                }
                return Json(AjaxResult.Error(strError));
            }
            return View(entity);
        }

        [Permission(IsParent =true)]
        public IActionResult GetColumns(LigerGrid ligerGrid, string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                var dbColumns = mCService.GetColumns(id.ToInt());
                ligerGrid.Rows = dbColumns;
                if (dbColumns != null)
                {
                    ligerGrid.Total = dbColumns.Count;
                }
            }
            return Json(ligerGrid);
        }
        [HttpPost]
        [Permission(IsParent = true)]
        public JsonResult DbSourceForGrid(LigerGrid grid,int id)
        {
            if (id <= 0)
            {
                return Json(grid);
            }
            return Json(mCService.GetDbSource(grid,id));
        }

        /// <summary>
        /// 执行导出并生成文件
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="data"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [Permission("03","导出")]
        public IActionResult Export(LigerGrid grid,string groupWhere, int id)
        {
            if (!string.IsNullOrWhiteSpace(groupWhere))
            {
                grid.Group = JSONHelper.FromJson<GroupFilter>(groupWhere);
            }
            var buffer = mCService.Export(grid, id);
            if (buffer != null&& buffer.Length>0)
            {
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
            }
            else
            {
                return Json(AjaxResult.Error("导出失败，请联系管理员"));
            }

        }
        [HttpPost]
        [Permission(ActionName = "SaveColumns")]
        public IActionResult SaveColumnsCell(string id,DbColumnEntity dbColumn)
        {
            string strError = "";
            if (mCService.SaveColumnsCell(id, dbColumn, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            else
            {
                return Json(AjaxResult.Error(strError));
            }
        }
        [Permission("04", "导入")]
        [HttpPost]
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        public IActionResult Import(string serverid)
        {
          //  string strError = "";
            //if (mService.Import(serverid, ref strError))
            //{
            //    strError = JSONHelper.ToJson(AjaxResult.Success(strError));
            //}
            //else
            //{
            //    strError = JSONHelper.ToJson(AjaxResult.Error(strError));
            //}
            //return ResultImport(strError);
            return View();
        }

        [HttpPost]
        public IActionResult CreateCode(int tableid, string templateid)
        {
            string strResult = "";
            if (mCService.CreateCode(tableid, templateid, ref strResult))
            {
                return Json(AjaxResult.Success(strResult,""));
            }
            return Json(AjaxResult.Error(strResult));
        }

        [HttpPost]
        [Permission(IsParent =true)]
        public IActionResult GetTemplate(string parentid)
        {
            var items = dTService.GetChildren(parentid);
            if (string.IsNullOrWhiteSpace(parentid))
            {
                if (items != null && items.Count > 0)
                {
                    items.ForEach(x => {
                        x.ParentId = "000";
                    });
                }
                return Json(AjaxResult.Success(new {
                    id= "000",
                    text="所有模板",
                    icon= "fa fa-file-code-o",
                    children=items.ToArray()
                }));
            }
            return Json(AjaxResult.Success(items));
        }

        /// <summary>
        /// 批量生成模板
        /// </summary>
        /// <param name="tableid"></param>
        /// <param name="templateid"></param>
        /// <param name="round"></param>
        /// <param name="maxtable"></param>
        /// <returns></returns>
        [HttpPost]
        [Permission("05","批量生成代码")]
        public async Task<IActionResult> CreateCodes(string tableid, string templateid,int round=0,int maxtable=0)
        {
            await mCService.CreateCodes(tableid, templateid, round, maxtable);
            return Json(AjaxResult.Success( ApplicationEnvironments.TempPath + "code.zip",""));
        }
        [HttpPost]
        [Permission("06", "数据同步")]
        public IActionResult syncTableData(int tableid,LigerGrid ligerGrid)
        {
            string strError = "";
            if (mCService.syncTableData(tableid, ligerGrid, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            return Json(AjaxResult.Error(strError));

        }
        [HttpPost]
        [Permission("07", "同步表结构")]
        public IActionResult syncTableStruct(int tableid)
        {
            string strError = "";
            if (mCService.syncTableStruct(tableid, ref strError))
            {
                return Json(AjaxResult.Success());
            }
            return Json(AjaxResult.Error(strError));

        }
       
    }
}